package com.think.oauth.user.security.token;

import java.util.Collection;
import java.util.Map;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;

import com.think.common.model.CustomUser;

public class AdditionalUserAuthenticationConverter extends DefaultUserAuthenticationConverter{
private Collection<? extends GrantedAuthority> defaultAuthorities;
		
	
	public AdditionalUserAuthenticationConverter() {
	}
	
	@Override
	public Authentication extractAuthentication(Map<String, ?> map) {
		if (map.containsKey(USERNAME) && map.containsKey("loginType")) {
			Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
			CustomUser user = new CustomUser(map.get(USERNAME)+"", "N/A", authorities, (Integer)map.get("loginType"),
					(Integer)map.get("userId"));
			
			return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
		}
		return null;
	}
	
	private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
		if (!map.containsKey(AUTHORITIES)) {
			return defaultAuthorities;
		}
		Object authorities = map.get(AUTHORITIES);
		if (authorities instanceof String) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
		}
		if (authorities instanceof Collection) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
					.collectionToCommaDelimitedString((Collection<?>) authorities));
		}
		throw new IllegalArgumentException("Authorities must be either a String or a Collection");
	}
}
